<?php

namespace app\common\model\mycurrency;

use think\Model;


class AgentMoneylog extends Model
{

    

    

    // 表名
    protected $name = 'mycurrency_agent_money_log';

    // 追加属性
    protected $append = [
        'type_text'
    ];

    const TYPE_HOUTAITIANJIA = 1;//余额变动类型 -后台添加
    const TYPE_HOUTAIJIANSHAO = 2;//余额变动类型 -后台减少
    const TYPE_YONGHUXIAOFEI = 3;//余额变动类型 - 用户消费收益
    const TYPE_TIXIAN = 4;//余额变动类型 - 代理商提现
    const TYPE_TIXIANBOHUI = 5;//余额变动类型 - 代理商提现驳回

    /**
     * 处理余额变动
     * @param int $agent_id 代理商ID
     * @param int $money 变动金额
     * @param  int $type 变动类型
     * @param array $data 数据
     */
    public static function moneyChange($agent_id,$money,$type,$data=[])
    {
        $agent = Agent::get($agent_id);
        $before = $agent['money'];//变更前余额
        $after = 0;//变更后余额
        if($type == self::TYPE_HOUTAITIANJIA || $type == self::TYPE_YONGHUXIAOFEI || $type == self::TYPE_TIXIANBOHUI){//后台添加  用户消费收益  提现驳回
            $after = $before + $money;
        }elseif ($type == self::TYPE_HOUTAIJIANSHAO || $type == self::TYPE_TIXIAN){
            $after = $before - $money;
        }
        $agent->money = $after;
        $agent->save();

        $insertData = [
            'agent_id' => $agent['id'],
            'money' => $money,
            'before' => $before,
            'after' => $after,
            //'memo' => '',
            'createtime' => time(),
            'type' => $type
        ];
        $data = array_merge($insertData,$data);
        self::create($data);
    }


    public function getCreatetimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }

    
    public function getTypeList()
    {
        return ['1' => __('后台添加'), '2' => __('后台减少'), '3' => __('用户消费收益'), '4' => __('代理商提现'), '5' => __('代理商提现驳回')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function agent()
    {
        return $this->belongsTo('app\admin\model\mycurrency\Agent', 'agent_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function withdrawal()
    {
        return $this->belongsTo('app\admin\model\mycurrency\AgentMoneyWithdrawal', 'withdrawal_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function profit()
    {
        return $this->belongsTo('app\admin\model\mycurrency\AgentProfit', 'profit_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
